package app.directive;

import app.constant.ProductConstant;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateNumberModel;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * <p> </p>
 *
 * @author sogYF
 * @version 1.0
 * @since JDK 1.6
 */
public class ProductProgressDirective implements TemplateDirectiveModel {
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        if (params.isEmpty()) {
            throw new TemplateModelException(
                    "This directive doesn't allow parameters.");
        }
        Writer out = env.getOut();

        TemplateNumberModel statusValue = (TemplateNumberModel) params.get("status");

        int status = statusValue.getAsNumber().intValue();
        switch (status){
            case ProductConstant.EMPTY:
            case ProductConstant.END:
            case ProductConstant.END_SALES:
            case ProductConstant.FOUND:
                out.write("100");
                break;
            case ProductConstant.ONLINE:

                TemplateNumberModel progressValue = (TemplateNumberModel) params.get("progress");
                TemplateNumberModel raised_mountValue = (TemplateNumberModel) params.get("raised_mount");
                int progress = progressValue.getAsNumber().intValue();
                double raised_mount = raised_mountValue.getAsNumber().doubleValue();
                if(raised_mount > 0 && raised_mount == 0){
                    out.write("1");
                } else {
                    out.write(String.valueOf(progress));
                }
                break;
        }


    }
}
